package com.xy.mainp.huaban.fragment;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.xy.mainp.HuaBanImgBinding;
import com.xy.mainp.R;
import com.xy.mainp.base.LazyFragment;
import com.xy.mainp.huaban.activity.ImgDetailActivity;
import com.xy.mainp.huaban.widget.ItemImgView;
import com.xy.mainp.model.huaban.ImgEntity;
import com.xy.mainp.utils.NetRequestUtils;
import com.xy.net.OkHttpUtils;
import com.xy.view.recyclerview.StandardAdapter;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Request;

import static android.app.Activity.RESULT_OK;
import static com.xy.mainp.BR.imgEntity;

/**
 * Created by John on 2016/11/18.
 */

public class ImagFragment extends LazyFragment implements SwipeRefreshLayout.OnRefreshListener {

    private HuaBanImgBinding binding;
    private ImgMsgAdapter adapter;
    private String mCategoryUrl;
    private String Result;
    private List<ImgEntity> list;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.fragment_huaban_img, null, false);
        setContentView(binding.getRoot());
        initView();
    }

    public void setmCategoryUrl(String mCategoryUrl) {
        this.mCategoryUrl = mCategoryUrl;
    }

    public ImagFragment() {
    }

    public ImagFragment(String mCategoryUrl) {
        this.mCategoryUrl = mCategoryUrl;
    }

    @Override
    protected void onShow() {
        super.onShow();
        loadNetData(mCategoryUrl);
    }

    private void loadNetData(String mCategoryUrl) {
        showLoading(true);

        NetRequestUtils.getInstance(getContext()).getHuaBanData(mCategoryUrl, new OkHttpUtils.ResultCallBack<String>() {
            @Override
            public void onError(Request request, Exception e) {
                if (TextUtils.isEmpty(e.getMessage())) {
                    if (binding.srlHuabanImg.isRefreshing()) {
                        binding.srlHuabanImg.setRefreshing(false);
                    }
                    showLoading(false);
                    showToastMsg(e.getMessage());
                }
            }

            @Override
            public void onResult(String result) {
                Result = result;
                Document document = Jsoup.parse(Result);
                showLoading(false);
                loadImgData(document);
            }
        });

    }

    private void loadImgData(Document document) {
        if (binding.srlHuabanImg.isRefreshing()) {
            binding.srlHuabanImg.setRefreshing(false);
        }

        Element element = document.select("div.waterfall").first();
        if (element != null) {
            Elements elements = element.select("div.pin-item");
            list = new ArrayList<>();
            for (Element img : elements) {
                ImgEntity imgEntity = new ImgEntity();
                String imgUrl = img.select("a").select("img").attr("src").toString();    //图片链接
                imgUrl = "http:" + imgUrl;
                String imgWidth = img.select("a").select("img").attr("width").toString();  //宽高
                String imgHeight = img.select("a").select("img").attr("height").toString();
                String desc = img.select("div.info div.description").first() == null ? "" : img.select("div.info div.description").first().text();  //简介
                String authorImg = img.select("div.author a img").attr("src").toString(); //作者头像
                authorImg = "http:" + authorImg;
                String title = img.select("div.author a").attr("title").toString();  //作者名字
                imgEntity.setImgUrl(imgUrl);
                imgEntity.setImgWidth(imgWidth);
                imgEntity.setImgHeight(imgHeight);
                imgEntity.setDesc(desc);
                imgEntity.setAuthorImg(authorImg);
                imgEntity.setTitle(title);
                list.add(imgEntity);
            }
            adapter.setData(list);
        } else {
            showToastMsg("根据相关规定，无法搜索");
        }
    }


    private void initView() {
        binding.srlHuabanImg.setOnRefreshListener(this);
        //加载颜色是循环播放的，只要没有完成刷新就会一直循环，color1>color2>color3>color4
        binding.srlHuabanImg.setColorSchemeResources(R.color.blue_60, R.color.yellow_f2);

        final StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        binding.rvHuabanImg.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                layoutManager.invalidateSpanAssignments();
                super.onScrollStateChanged(recyclerView, newState);
            }
        });
        adapter = new ImgMsgAdapter();
        binding.rvHuabanImg.setLayoutManager(layoutManager);
        binding.rvHuabanImg.setAdapter(adapter);

        adapter.setItemClickListener(new StandardAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                Intent intent = new Intent();
                intent.putExtra("images", (ArrayList<ImgEntity>) list);//非必须
                intent.putExtra("position", position);
                ImgDetailActivity.enter(intent, getActivity());
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                int selectedPosition = data.getIntExtra("selectedPosition", 0);
                binding.rvHuabanImg.scrollToPosition(selectedPosition);
                Log.i("selectedPosition", selectedPosition + "");
            }
        }
    }

    @Override
    public void onRefresh() {
        loadNetData(mCategoryUrl);
    }

    class ImgMsgAdapter extends StandardAdapter {
        @Override
        public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            ItemImgView itemImgView = new ItemImgView(parent.getContext());
            itemImgView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            return new ItemViewHolder(itemImgView);
        }

        @Override
        public void onBindViewHolder(ItemViewHolder holder, int position) {
            super.onBindViewHolder(holder, position);
            ImgEntity imgEntity = (ImgEntity) getItem(position);
            ((ItemImgView) holder.itemView).setData(imgEntity);
        }

    }
}
